package cn.xqapp.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.function.Supplier;

public class BaseServer implements Runnable {

    protected int port;
    protected Supplier<ChannelHandler> channelHandlerSupplier;

    protected Runnable onBeforeRunHandler;
    protected Runnable onBeforeShutdownHandler;

    public BaseServer(int port){
        this(port, null);
    }

    public BaseServer(int port, Supplier<ChannelHandler> channelHandlerSupplier){
        this.port = port;
        this.channelHandlerSupplier = channelHandlerSupplier;
    }

    protected void setChannelHandlerSupplier(Supplier<ChannelHandler> channelHandlerSupplier) {
        this.channelHandlerSupplier = channelHandlerSupplier;
    }

    protected void safeNotifyEvent(Runnable eventHandler){
        if(eventHandler != null){
            eventHandler.run();
        }
    }
    public void onBeforeRun(Runnable beforeRunHandler){
        this.onBeforeRunHandler = beforeRunHandler;
    }
    public void onBeforeShutdown(Runnable shutdownHandler){
        this.onBeforeShutdownHandler = shutdownHandler;
    }

    public void run(){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(channelHandlerSupplier.get())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(this.port).sync();
            safeNotifyEvent(this.onBeforeRunHandler);

            f.channel().closeFuture().sync();
            safeNotifyEvent(this.onBeforeShutdownHandler);

        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }finally{
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}

